package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper groupMapper;

    @Autowired
    private SpecParamMapper paramMapper;

    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        SpecGroup group = new SpecGroup();
        group.setCid(id);
        List<SpecGroup> list = groupMapper.select(group);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

    public List<SpecParamDTO> queryParams(Long gid, Long cid, Boolean searching) {
        // 判断不能都为空
        if (gid == null && cid == null && searching == null) {
            // 400
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        SpecParam param = new SpecParam();
        param.setGroupId(gid);
        param.setCid(cid);
        param.setSearching(searching);
        // 根据param 的非空字段查询
        List<SpecParam> list = paramMapper.select(param);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecsOfCategory(Long id) {
        // 1.查询分类下的规格组
        List<SpecGroupDTO> groupList = queryGroupByCategory(id);

        // 2.查询出分类下的 的参数的集合
        List<SpecParamDTO> params = queryParams(null, id, null);

        // 3.对param分组，根据groupId分。放入一个Map，map的key:groupId,值是id一致的param集合
        Map<Long, List<SpecParamDTO>> map = params.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 4.根据组id，查询组内参数
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupList;
    }
}
